﻿namespace WpfDataStreamDemo.Repository
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Threading;

    namespace Streaming.Demo.Repository
    {
        internal static class StreamRepository
        {
            public static IEnumerable<DataRow> GetTest()
            {
                const string query = "SELECT * FROM Streaming.TestView";
                var testTable = CreateDataTable(query);
                var reader = DataAdapter.StreamingDataAdapter.ExecuteQueryReader(query, null);
                var rowValues = new object[reader.FieldCount];
                while (reader.Read())
                {
                    reader.GetValues(rowValues);
                    yield return testTable.LoadDataRow(rowValues, true);
                }
            }

            public static IEnumerable<DataRow> GetTestWithLatency()
            {
                const string query = "SELECT * FROM Streaming.TestView";
                var testTable = CreateDataTable(query);
                var reader = DataAdapter.StreamingDataAdapter.ExecuteQueryReader(query, null);
                var rowValues = new object[reader.FieldCount];
                while (reader.Read())
                {
                    reader.GetValues(rowValues);
                    Thread.Sleep(new Random().Next(100, 1500));
                    yield return testTable.LoadDataRow(rowValues, true);
                }
            }

            private static DataTable CreateDataTable(string query)
            {
                using (var schemaReader =
                    DataAdapter.StreamingDataAdapter.ExecuteQueryReader(string.Format("SET FMTONLY ON; {0}; SET FMTONLY OFF", query), null))
                {
                    var dataTable = new DataTable();
                    dataTable.Load(schemaReader);
                    return dataTable;
                }
            }
        }
    }

}
